﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.EnterpriseServices;
using System.Web.Services;

public partial class DeliverGoodsManagement_InvoiceDetails : System.Web.UI.Page//, ICallbackEventHandler
{
    public string strResult;

    #region 属性

    private string DeletedOrderDetailID
    {
        get
        {
            string str = "";
            if (ViewState["DeletedOrderDetailID"] != null)
            {
                str = ViewState["DeletedOrderDetailID"].ToString();
            }
            return str;
        }
        set
        {
            ViewState["DeletedOrderDetailID"] = value;
        }
    }

    private bool IsSend
    {
        get
        {
            bool isSend = false;
            if (ViewState["IsSend"] != null)
            {
                isSend = Convert.ToBoolean(ViewState["IsSend"]);
            }
            return isSend;
        }
        set
        {
            ViewState["IsSend"] = value;
        }
    }

    private bool IsClear
    {
        get
        {
            bool isClear = false;
            if (ViewState["IsClear"] != null)
            {
                isClear = Convert.ToBoolean(ViewState["IsClear"]);
            }
            return isClear;
        }
        set
        {
            ViewState["IsClear"] = value;
        }
    }

    private string Traner
    {
        get
        {
            string traner = string.Empty;
            if (ViewState["Traner"] != null)
            {
                traner = ViewState["Traner"].ToString();
            }
            return traner;
        }
        set
        {
            ViewState["Traner"] = value;
        }
    }

    private string Code
    {
        get
        {
            return Request.QueryString["code"] != null ? Request.QueryString["code"].ToString() : "";
        }
    }

    private DataSet InvoiceDetails
    {
        get
        {
            DataSet dst = null;
            if (ViewState["InvoiceDetails"] != null)
            {
                dst = (DataSet)ViewState["InvoiceDetails"];
            }
            return dst;
        }
        set
        {
            ViewState["InvoiceDetails"] = value;
        }
    }

    private string OrderStateTypeCode
    {
        get
        {
            string orderStateTypeCode = "";
            if (ViewState["OrderStateTypeCode"] != null)
            {
                orderStateTypeCode = ViewState["OrderStateTypeCode"].ToString();
            }
            return orderStateTypeCode;
        }
        set
        {
            ViewState["OrderStateTypeCode"] = value;
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        this.form1.DefaultButton = "btnHiddenShip";
        Check.CheckPermission("500100");
        if (!IsPostBack)
        {
            BindTraner();
            BindInvoice();
            BindInvoiceDetails();
            BindOrderNote();
            ButtonStatus();
            if (this.IsSend)
            {
                btnSave.Enabled = false;
                btnDeliver.Enabled = false;
            }
            btnDeliver.Attributes.Add("onclick", "Mask();");
        }
    }

    #region 控件绑定

    private void BindTraner()
    {
        dropExpressBill.DataSource = new BLL.ExpressBillTemplate().GetTranerAndExpressBillTemplate();
        dropExpressBill.DataTextField = "TranerTemplateName";
        dropExpressBill.DataValueField = "TranerTemplateId";
        dropExpressBill.DataBind();
        ListItem item = new ListItem();
        item.Text = "      ";
        item.Value = "-1";
        dropExpressBill.Items.Insert(0, item);
    }

    private void BindInvoice()
    {
        DataSet dst = new BLL.ORDERDOC().GetOrder(this.Code);
        if (dst != null && dst.Tables.Count > 0 && dst.Tables[0].Rows.Count > 0)
        {
            this.IsSend = dst.Tables[0].Rows[0]["ORDER_SEND"].ToString() == "1" ? true : false;
            this.IsClear = dst.Tables[0].Rows[0]["ORDER_CLEAR"].ToString() == "1" ? true : false;
            this.OrderStateTypeCode = dst.Tables[0].Rows[0]["ORDER_STATETYPECODE"].ToString();
            this.Traner = dst.Tables[0].Rows[0]["ORDER_TRANERCODE"].ToString();
            dlistMainInvoice.DataSource = dst;
            dlistMainInvoice.DataBind();

        }
    }

    private void BindInvoiceDetails()
    {
        this.InvoiceDetails = new BLL.ORDERDETAIL().GetOrderDetail(this.Code);
        grvInvoiceDetail.DataSource = this.InvoiceDetails;
        grvInvoiceDetail.DataBind();
    }

    private void BindOrderNote()
    {
        DataSet dst = new BLL.ORDERNOTE().GetOrderNoteById(this.Code);
        ORDERNOTEListControl1.Bind(dst);
    }
    #endregion

    #region 控件事件
    protected void grvInvoiceDetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (!Check.CheckPermission("500100", "00003"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
        if (order != null)
        {
            if (order.ORDER_SEND == 1)
            {
                Share.Alert(this.Page, "该订单已做发货，不能再编辑！"); return;
            }
        }
        this.DeletedOrderDetailID += "'" + grvInvoiceDetail.DataKeys[e.RowIndex].Value.ToString() + "',";
        this.InvoiceDetails.Tables[0].Rows.RemoveAt(e.RowIndex);
        string s = hidQty.Value;
        hid.Value = "2";
        grvInvoiceDetail.DataSource = this.InvoiceDetails;
        grvInvoiceDetail.DataBind();
        hidQty.Value = s;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (!Check.CheckPermission("500100", "00017"))
            {
                Share.Alert(this.Page, "无权操作"); return;
            }

            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
            if (order != null)
            {
                if (order.ORDER_SEND==0)
                {
                    if (hid.Value == "0")
                    {
                        List<Model.ORDERDETAIL> orderDetails;
                        int pageCount, recordCount;
                        if (this.DeletedOrderDetailID != "")
                        {
                            char[] charToTrim = new char[] { ',' };
                            orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + this.Code + "' and OD_DETAILID not in(" + this.DeletedOrderDetailID.TrimEnd(charToTrim) + ")", out pageCount, out recordCount);
                        }
                        else
                        {
                            orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + this.Code + "'", out pageCount, out recordCount);
                        }
                        if (orderDetails != null)
                        {


                            List<Model.ORDERDETAIL> newOrderDetails = new List<Model.ORDERDETAIL>();
                            Model.ORDERDETAIL newOrderDetail;
                            List<Model.ORDERDETAIL> toUpdateOrderDetails = new List<Model.ORDERDETAIL>();
                            decimal quantity;
                            string notes;
                            decimal points;
                            decimal weight;
                            foreach (Model.ORDERDETAIL tempDetail in orderDetails)
                            {
                                for (int i = 0; i < grvInvoiceDetail.Rows.Count; i++)
                                {
                                    if (tempDetail.OD_DETAILID == grvInvoiceDetail.DataKeys[i].Value.ToString())
                                    {
                                        quantity = decimal.Parse(((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtQty")).Text);
                                        notes = ((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtNotes")).Text;
                                        points = decimal.Parse(((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtPoints")).Text);
                                        weight = decimal.Parse(((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtWeight")).Text);
                                        if (quantity > 0 && points >= 0 && weight >= 0)
                                        {
                                            if (quantity < tempDetail.OD_QTY)
                                            {
                                                newOrderDetail = new Model.ORDERDETAIL();
                                                newOrderDetail.OD_ID = tempDetail.OD_ID;

                                                newOrderDetail.OD_ID = tempDetail.OD_ID;
                                                newOrderDetail.OD_DETAILID = tempDetail.OD_DETAILID;
                                                newOrderDetail.OD_CMDCODE = tempDetail.OD_CMDCODE;
                                                newOrderDetail.OD_COLORCODE = tempDetail.OD_COLORCODE;
                                                newOrderDetail.OD_SIZECODE = tempDetail.OD_SIZECODE;
                                                newOrderDetail.OD_QTY = tempDetail.OD_QTY - quantity;
                                                newOrderDetail.OD_SENDQTY = tempDetail.OD_SENDQTY;
                                                newOrderDetail.OD_SPRICE = tempDetail.OD_SPRICE;
                                                newOrderDetail.OD_DISC = tempDetail.OD_DISC;
                                                newOrderDetail.OD_APRICE = tempDetail.OD_APRICE;
                                                newOrderDetail.OD_SAMT = newOrderDetail.OD_QTY * newOrderDetail.OD_SPRICE;
                                                newOrderDetail.OD_AAMT = newOrderDetail.OD_QTY * newOrderDetail.OD_APRICE;
                                                newOrderDetail.OD_NOTE = notes;
                                                newOrderDetail.OD_FIELD1 = tempDetail.OD_FIELD1;
                                                newOrderDetail.OD_FIELD2 = tempDetail.OD_FIELD2;
                                                newOrderDetail.OD_SPPRICE = tempDetail.OD_SPPRICE;
                                                newOrderDetail.OD_GIFT = tempDetail.OD_GIFT;
                                                newOrderDetail.OD_ITGBUY = tempDetail.OD_ITGBUY;
                                                newOrderDetail.OD_ITGPRICE = tempDetail.OD_ITGPRICE;
                                                newOrderDetail.OD_ITG = ((tempDetail.OD_QTY - quantity) / tempDetail.OD_QTY) * tempDetail.OD_ITG;
                                                newOrderDetail.OD_ADDITG = tempDetail.OD_ADDITG;
                                                newOrderDetail.OD_WEIGHT = weight;
                                                newOrderDetail.OD_OFFER = tempDetail.OD_OFFER;
                                                newOrderDetail.OD_OFFERTYPE = tempDetail.OD_OFFERTYPE;
                                                newOrderDetail.OD_OFFERID = tempDetail.OD_OFFERID;
                                                newOrderDetail.OD_OFFERNO = tempDetail.OD_OFFERNO;
                                                newOrderDetails.Add(newOrderDetail);

                                                tempDetail.OD_QTY = quantity;
                                                tempDetail.OD_AAMT = tempDetail.OD_APRICE * quantity;
                                                tempDetail.OD_SAMT = tempDetail.OD_SPRICE * quantity;
                                                tempDetail.OD_NOTE = notes;
                                                tempDetail.OD_ITG = points;
                                                tempDetail.OD_WEIGHT = weight;
                                                toUpdateOrderDetails.Add(tempDetail);
                                            }
                                            else if (quantity == tempDetail.OD_QTY)
                                            {
                                                tempDetail.OD_NOTE = notes;
                                                toUpdateOrderDetails.Add(tempDetail);
                                            }
                                            else
                                            {
                                                throw new Exception("发货数不可以大于订单数！");
                                            }

                                        }
                                        else
                                        {
                                            throw new Exception("请填写正确的数字！数量必须大于0！");
                                        }
                                    }
                                }
                            }

                            bool result = new BLL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(false, this.Code, this.DeletedOrderDetailID, newOrderDetails, toUpdateOrderDetails, Share.UserValue(0), ConfigurationManager.AppSettings["ckdm"].ToString(), ConfigurationManager.AppSettings["kwdm"].ToString(), ((DropDownList)dlistMainInvoice.Items[0].FindControl("dropTraner")).SelectedValue);
                            if (result)
                            {
                                Share.InsertLog("500100", "00017");
                                hidQty.Value = "";
                                hid.Value = "2";
                                BindInvoice();
                                BindInvoiceDetails();
                                BindOrderNote();
                                Share.Alert(this.Page, "修改成功！");
                            }
                            else
                            {
                                hidQty.Value = "";
                                hid.Value = "2";
                                BindInvoice();
                                BindInvoiceDetails();
                                Share.Alert(this.Page, "修改失败，请重新编辑！");
                            }
                        }
                    }
                    else if (hid.Value == "1")
                    {
                        List<Model.ORDERDETAIL> orderDetails;
                        int pageCount, recordCount;
                        if (this.DeletedOrderDetailID != "")
                        {
                            char[] charToTrim = new char[] { ',' };
                            orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + this.Code + "' and OD_DETAILID not in(" + this.DeletedOrderDetailID.TrimEnd(charToTrim) + ")", out pageCount, out recordCount);
                        }
                        else
                        {
                            orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + this.Code + "'", out pageCount, out recordCount);
                        }
                        if (orderDetails != null)
                        {

                            List<Model.ORDERDETAIL> newOrderDetails = new List<Model.ORDERDETAIL>();
                            Model.ORDERDETAIL newOrderDetail;
                            List<Model.ORDERDETAIL> toUpdateOrderDetails = new List<Model.ORDERDETAIL>();
                            decimal quantity;
                            string notes;
                            decimal points;
                            decimal weight;
                            foreach (Model.ORDERDETAIL tempDetail in orderDetails)
                            {
                                for (int i = 0; i < grvInvoiceDetail.Rows.Count; i++)
                                {
                                    if (tempDetail.OD_DETAILID == grvInvoiceDetail.DataKeys[i].Value.ToString())
                                    {
                                        quantity = decimal.Parse(((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtQty")).Text);
                                        notes = ((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtNotes")).Text;
                                        points = decimal.Parse(((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtPoints")).Text);
                                        weight = decimal.Parse(((TextBox)grvInvoiceDetail.Rows[i].FindControl("txtWeight")).Text);
                                        if (quantity > 0 && points >= 0 && weight >= 0)
                                        {
                                            if (quantity < tempDetail.OD_QTY)
                                            {
                                                newOrderDetail = new Model.ORDERDETAIL();
                                                newOrderDetail.OD_ID = tempDetail.OD_ID;

                                                newOrderDetail.OD_ID = tempDetail.OD_ID;
                                                newOrderDetail.OD_DETAILID = tempDetail.OD_DETAILID;
                                                newOrderDetail.OD_CMDCODE = tempDetail.OD_CMDCODE;
                                                newOrderDetail.OD_COLORCODE = tempDetail.OD_COLORCODE;
                                                newOrderDetail.OD_SIZECODE = tempDetail.OD_SIZECODE;
                                                newOrderDetail.OD_QTY = tempDetail.OD_QTY - quantity;
                                                newOrderDetail.OD_SENDQTY = tempDetail.OD_SENDQTY;
                                                newOrderDetail.OD_SPRICE = tempDetail.OD_SPRICE;
                                                newOrderDetail.OD_DISC = tempDetail.OD_DISC;
                                                newOrderDetail.OD_APRICE = tempDetail.OD_APRICE;
                                                newOrderDetail.OD_SAMT = newOrderDetail.OD_QTY * newOrderDetail.OD_SPRICE;
                                                newOrderDetail.OD_AAMT = newOrderDetail.OD_QTY * newOrderDetail.OD_APRICE;
                                                newOrderDetail.OD_NOTE = notes;
                                                newOrderDetail.OD_FIELD1 = tempDetail.OD_FIELD1;
                                                newOrderDetail.OD_FIELD2 = tempDetail.OD_FIELD2;
                                                newOrderDetail.OD_SPPRICE = tempDetail.OD_SPPRICE;
                                                newOrderDetail.OD_GIFT = tempDetail.OD_GIFT;
                                                newOrderDetail.OD_ITGBUY = tempDetail.OD_ITGBUY;
                                                newOrderDetail.OD_ITGPRICE = tempDetail.OD_ITGPRICE;
                                                newOrderDetail.OD_ITG = ((tempDetail.OD_QTY - quantity) / tempDetail.OD_QTY) * tempDetail.OD_ITG;
                                                newOrderDetail.OD_ADDITG = tempDetail.OD_ADDITG;
                                                newOrderDetail.OD_WEIGHT = weight;
                                                newOrderDetail.OD_OFFER = tempDetail.OD_OFFER;
                                                newOrderDetail.OD_OFFERTYPE = tempDetail.OD_OFFERTYPE;
                                                newOrderDetail.OD_OFFERID = tempDetail.OD_OFFERID;
                                                newOrderDetail.OD_OFFERNO = tempDetail.OD_OFFERNO;
                                                newOrderDetails.Add(newOrderDetail);

                                                tempDetail.OD_QTY = quantity;
                                                tempDetail.OD_AAMT = tempDetail.OD_APRICE * quantity;
                                                tempDetail.OD_SAMT = tempDetail.OD_SPRICE * quantity;
                                                tempDetail.OD_NOTE = notes;
                                                tempDetail.OD_ITG = points;
                                                tempDetail.OD_WEIGHT = weight;
                                                toUpdateOrderDetails.Add(tempDetail);
                                            }
                                            else if (quantity == tempDetail.OD_QTY)
                                            {
                                                tempDetail.OD_NOTE = notes;
                                                toUpdateOrderDetails.Add(tempDetail);
                                            }
                                            else
                                            {
                                                throw new Exception("发货数不可以大于订单数！");
                                            }

                                        }
                                        else
                                        {
                                            throw new Exception("请填写正确的数字！数量必须大于0！");
                                        }
                                    }
                                }
                            }

                            bool result = new BLL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(true, this.Code, this.DeletedOrderDetailID, newOrderDetails, toUpdateOrderDetails, Share.UserValue(0), ConfigurationManager.AppSettings["ckdm"].ToString(), ConfigurationManager.AppSettings["kwdm"].ToString(), ((DropDownList)dlistMainInvoice.Items[0].FindControl("dropTraner")).SelectedValue);
                            if (result)
                            {
                                Share.InsertLog("500100", "00017");
                                hidQty.Value = "";
                                hid.Value = "2";
                                BindInvoice();
                                BindInvoiceDetails();
                                BindOrderNote();
                                Share.Alert(this.Page, "修改成功！");
                            }
                            else
                            {
                                hidQty.Value = "";
                                hid.Value = "2";
                                BindInvoice();
                                BindInvoiceDetails();
                                Share.Alert(this.Page, "修改失败，请重新编辑！");
                            }
                        }
                    }
                    else
                    {
                        string[] strSql = new string[] { "update orderdoc set ORDER_TRANERCODE='" + ((DropDownList)dlistMainInvoice.Items[0].FindControl("dropTraner")).SelectedValue + "' where order_id='" + this.Code + "'" };
                        if (new BLL.ORDERDETAIL().UpdateOrderDetailAndOrderMain(strSql))
                        {
                            Share.InsertLog("500100", "00017");
                            hidQty.Value = "";
                            hid.Value = "2";
                            BindInvoice();
                            BindInvoiceDetails();
                            BindOrderNote();
                            Share.Alert(this.Page, "修改成功！");
                        }
                        else
                        {
                            hidQty.Value = "";
                            hid.Value = "2";
                            BindInvoice();
                            BindInvoiceDetails();
                            Share.Alert(this.Page, "修改失败，请重新编辑！");
                        }
                    }
                }
                else
                {
                    Share.Alert(this.Page, "该订单已做发货和结算操作，不可以再修改订单！");
                }
            }
            
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
       
    }

    protected void btnAddSuggestion_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("500100", "00021"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        Response.Redirect("AddSuggestion.aspx?code=" + this.Code +"&stCode=" + this.OrderStateTypeCode);
    }

    protected void grvInvoiceDetail_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txtQty = (TextBox)e.Row.FindControl("txtQty");
            TextBox txtPoints = (TextBox)e.Row.FindControl("txtPoints");
            TextBox txtWeight = (TextBox)e.Row.FindControl("txtWeight");
            TextBox txtNotes = (TextBox)e.Row.FindControl("txtNotes");
            Button btnDelete = (Button)e.Row.FindControl("btnDelete");
            if (this.IsSend)
            {
                txtQty.Enabled = false;
                txtPoints.Enabled = false;
                txtWeight.Enabled = false;
                txtNotes.Enabled = false;
                btnDelete.Enabled = false;
            }
            hidQty.Value += txtQty.Text + "|";
        }
    }

    protected void dlistMainInvoice_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //TextBox txtTranCost = (TextBox)e.Item.FindControl("txtTranCost");
            //TextBox txtOfferAMT = (TextBox)e.Item.FindControl("txtOfferAMT");
            //HtmlInputText txtDeliverCode = (HtmlInputText)e.Item.FindControl("txtDeliverCode");
            //if (this.IsSend)
            //{
            //    txtTranCost.Enabled = false;
            //    txtOfferAMT.Enabled = false;
            //}
            //this.Page.SetFocus(txtDeliverCode.ID);
            HtmlInputHidden hidTranerCode = (HtmlInputHidden)e.Item.FindControl("hidTranerCode");
            DropDownList dropTraner = (DropDownList)e.Item.FindControl("dropTraner");
            dropTraner.DataSource = new BLL.TRANER().GetAllList(true);
            dropTraner.DataTextField = "traner_name";
            dropTraner.DataValueField = "traner_code";
            dropTraner.DataBind();

            for (int i = 0; i < dropTraner.Items.Count; i++)
            {
                if (dropTraner.Items[i].Value == hidTranerCode.Value)
                {
                    dropTraner.SelectedIndex = i;
                    break;
                }
            }
        }
    }

    protected void btnExpressPrint_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("500100", "00020"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        if (dropExpressBill.SelectedIndex == 0)
        {
            Share.Alert(this.Page, "请选择物流单打印模板"); return;
        }
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
        if (order == null)
        {
            Share.Alert(this.Page, "更新物流单打印次数时出现错误，请重试！"); return;
        }
        order.ORDER_TPRINT = 1;
        order.ORDER_TPRINTER = Share.UserValue(0);
        order.ORDER_TPRINTDATE = DateTime.Now;
        order.ORDER_TPRINTCOUNT = order.ORDER_TPRINTCOUNT + 1;
        if (new BLL.ORDERDOC().Update(order))
        {
            Page.RegisterStartupScript("StartUp", "<script language=javascript>window.open('printwindow.aspx?tranerId=" + dropExpressBill.SelectedValue + "&orderId=" + this.Code + "')</script>");
        }
        else
        {
            Share.Alert(this.Page, "更新物流单打印次数时出现错误，请重试！"); return;
        }
    }
        
    protected void btnDeliverPrint_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("500100", "00020"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }

        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
        if (order == null)
        {
            Share.Alert(this.Page, "更新物流单打印次数时出现错误，请重试！"); return;
        }
        order.ORDER_PRINT = 1;
        order.ORDER_PRINTER = Share.UserValue(0);
        order.ORDER_PRINTDATE = DateTime.Now;
        order.ORDER_PRINTCOUNT = order.ORDER_PRINTCOUNT + 1;
        if (new BLL.ORDERDOC().Update(order))
        {
            string openurlstr = "";
            if (ConfigurationManager.AppSettings["IsXtlProject"].ToString() == "1")
            {
                Page.RegisterStartupScript("StartUp", "<script language=javascript>window.open('PrintDeliverBill.aspx?orderId=" + this.Code + "')</script>");
            }
            else if (ConfigurationManager.AppSettings["IsXtlProject"].ToString() == "0")
            {
                 Page.RegisterStartupScript("StartUp", "<script language=javascript>window.open('PrintDeliverBillWindow.aspx?orderId=" + this.Code + "')</script>"); 
               
            }
            else if (ConfigurationManager.AppSettings["IsXtlProject"].ToString() == "2")
            { 

                string sprinttype = "0";//默认打印时不显示界面
                if (ConfigurationManager.AppSettings["PrintType"] != null && ConfigurationManager.AppSettings["PrintType"] != "") sprinttype = ConfigurationManager.AppSettings["PrintType"];
                //By winner add打印
                //for (int i = 0; i < strOrderId.Split('|').Length; i++)
                //{
                openurlstr += "window.open('../BillReport.aspx?DJBH=" + this.Code + "&ReportModule=FHGL/SDFHD&ReportName=SDFHD&PrintType=" + sprinttype + "');";
                //}
                Page.RegisterStartupScript("StartUp", "<script language=javascript>" + openurlstr + "</script>");

            }
        }
        else
        {
            Share.Alert(this.Page, "更新配货单打印次数时出现错误，请重试！"); return;
        }
        //Page.RegisterStartupScript("StartUp", "<script language=javascript>window.open('PrintDeliverBillWindow.aspx?orderId=" + this.Code + "')</script>");
    }

    protected void btnDeliver_Click(object sender, EventArgs e)
    {
        try
        {
            if (!Check.CheckPermission("500100", "00014"))
            {
                Share.Alert(this.Page, "无权操作"); return;
            }

            
            Model.PICI pc = new BLL.PICI().GetModel(Share.UserValue(0), "PCH_ID");
            if (pc == null)
            {
                Share.Alert(this.Page, "请先开始一个批次"); return;
            }

            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
            HtmlInputText txtDeliverCode = (HtmlInputText)dlistMainInvoice.Items[0].FindControl("txtDeliverCode");
            if (txtDeliverCode.Value.Length <= 0)
            {
                Share.Alert(this.Page, "物流单号不允许少于4个字符长度!"); return;
            }
            DataSet ds = null;
            string ret = new BLL.ORDERDOC().GetOrderByWhere(string.Format(" where ORDER_TRANBILLCODE ='{0}' and ORDER_ID not in('{1}') ", txtDeliverCode.Value, this.Code), out ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                Share.Alert(this.Page, "物流单号不允许重复！"); return;
            }
            if (order.ORDER_SEND==0 || !this.IsClear)
            {
                this.programmaticModalPopup.Show();
                bool result = Deliver(this.Code, Share.UserValue(0), true, txtDeliverCode.Value,pc.PCH_ID);
                if (result)
                {
                    Share.InsertLog("500100", "00014");

                    //发货成功后给客户发送通知邮件
                    if (order != null)
                    {
                        List<Model.EMAILBODY> bodylist = new BLL.EMAILBODY().GetAllList();
                        if (bodylist != null)
                        {
                            if (bodylist.Count > 0)
                            {
                                Model.EMAILBODY body = bodylist[0];
                                if (body.DeliverySwitch == 1)
                                {
                                    Model.V_CUSTOMER customer = new BLL.V_CUSTOMER().GetModel(order.ORDER_CUSTOMERCODE);
                                    if (customer != null)
                                    {
                                        BLL.EmailSendBL bl = new BLL.EmailSendBL(customer.EMAIL, "DeliverySubject", "");
                                        bl.SendDeliveryEmail(this.Code);
                                    }
                                }
                            }
                        }
                    }
                    //Page.RegisterStartupScript("StartUp", "<script language=javascript>alert('发货成功！');location.href='InvoiceDetails.aspx?code=" + this.Code + "';</script>");
                    Page.RegisterStartupScript("StartUp", "<script language=javascript>alert('发货成功！');window.close();</script>");

                }
                else
                {
                    Share.Alert(this.Page, "执行发货时出现错误，请重新执行发货操作！");
                }
                this.programmaticModalPopup.Hide();
            }
            else
            {
                Share.Alert(this.Page, "该订单已做发货和结算操作，不能重复发货！");
            }
        }
        catch (Exception ex)
        {
            this.programmaticModalPopup.Hide();
            Share.Alert(this.Page, ex.Message);
        }

    }

    //此方法与发货单列表页面内的Deliver方法不同，不可覆盖

    public bool Deliver(string orderId, string operatorId, bool IsUpdateDeliverCode, string deliverCode,string pch)
    {

        int pageCount, recordCount;
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(orderId);
        List<Model.ORDERDETAIL> orderDetails = new BLL.ORDERDETAIL().GetList(100, 1, " OD_DETAILID ", false, " and OD_ID='" + orderId + "' ", out pageCount, out recordCount);
        IList<Model.PAYDETAIL> payDetails = new SQLServerDAL.PAYDETAIL().GetPayDetailById(orderId);
        if (order != null && orderDetails != null && payDetails != null)
        {
            if (order.ORDER_SEND == 1)
            {
                throw new Exception("该订单已发货");
            }
            if (orderDetails.Count == 0)
            {
                throw new Exception("系统无法查询到该订单的明细，不能执行发货操作！");
            }
            if (order.ORDER_APAY != 1)
            {
                if (payDetails.Count == 0)
                {
                    throw new Exception("系统无法查询到该订单的支付明细，不能执行发货操作！");
                }
            }
            if (order.ORDER_CHECK != 1 || order.ORDER_ACHECK != 1 || order.ORDER_DELETE != 0)
            {
                throw new Exception("订单不符合发货条件,未能发货！");
            }
            if (order.ORDER_ACHECKDATE > DateTime.Now)
            {
                throw new Exception("订单被反审校了,请确认后再发货！");
            }
            HtmlInputText txtDeliverCode = (HtmlInputText)dlistMainInvoice.Items[0].FindControl("txtDeliverCode");
            if (txtDeliverCode.Value.Length <= 4)
            {
                throw new Exception("物流单号不允许少于4个字符长度！"); 
            }
            DataSet ds = null;
            string ret = new BLL.ORDERDOC().GetOrderByWhere(string.Format(" where ORDER_TRANBILLCODE ='{0}' and ORDER_ID not in('{1}') ", txtDeliverCode.Value, this.Code), out ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                throw new Exception("物流单号不允许重复！"); 
            }
            #region 非货到付款流程


            if (order.ORDER_APAY == 0)
            {
                #region 含担保交易


                if (order.ORDER_SECDEAL == 1)
                {
                    StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                    StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                    Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                    if (userInfo == null)
                    {
                        throw new Exception("系统内无此会员信息！");
                    }
                    Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                    if (userAccount == null)
                    {
                        strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                        strSqlToUpdateBStyleDB.Append(userInfo.DM);
                        strSqlToUpdateBStyleDB.Append("',0)|");

                        strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                        strSqlToUpdateErpDB.Append(userInfo.DM);
                        strSqlToUpdateErpDB.Append("',0)|");

                    }
                    if (IsUpdateDeliverCode)
                    {
                        strSqlToUpdateBStyleDB.Append("update ORDERDOC set ORDER_SEND=1,ORDER_SENDER='");
                        strSqlToUpdateBStyleDB.Append(operatorId);
                        strSqlToUpdateBStyleDB.Append("',ORDER_SENDDATE='");
                        strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        strSqlToUpdateBStyleDB.Append("',ORDER_TRANBILLCODE='");
                        strSqlToUpdateBStyleDB.Append(deliverCode);
                        strSqlToUpdateBStyleDB.Append("',BYZD21='");
                        strSqlToUpdateBStyleDB.Append(pch);
                        strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(orderId);
                        strSqlToUpdateBStyleDB.Append("'|");
                    }
                    else
                    {
                        strSqlToUpdateBStyleDB.Append("update ORDERDOC set ORDER_SEND=1,ORDER_SENDER='");
                        strSqlToUpdateBStyleDB.Append(operatorId);
                        strSqlToUpdateBStyleDB.Append("',ORDER_SENDDATE='");
                        strSqlToUpdateBStyleDB.Append(DateTime.Now);
                        strSqlToUpdateBStyleDB.Append("',BYZD21='");
                        strSqlToUpdateBStyleDB.Append(pch);
                        strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                        strSqlToUpdateBStyleDB.Append(orderId);
                        strSqlToUpdateBStyleDB.Append("'|");
                    }

                    for (int i = 0; i < orderDetails.Count; i++)
                    {
                        strSqlToUpdateBStyleDB.Append("update SPKCB set SL=SL-");
                        strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_QTY);
                        strSqlToUpdateBStyleDB.Append(" where CKDM='");
                        strSqlToUpdateBStyleDB.Append(ConfigurationManager.AppSettings["ckdm"].ToString());
                        strSqlToUpdateBStyleDB.Append("' and KWDM='");
                        strSqlToUpdateBStyleDB.Append(ConfigurationManager.AppSettings["kwdm"].ToString());
                        strSqlToUpdateBStyleDB.Append("' and SPDM='");
                        strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_CMDCODE);
                        strSqlToUpdateBStyleDB.Append("' and GG1DM='");
                        strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_COLORCODE);
                        strSqlToUpdateBStyleDB.Append("' and GG2DM='");
                        strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_SIZECODE);
                        strSqlToUpdateBStyleDB.Append("'|");
                    }



                    if (strSqlToUpdateErpDB.ToString() == "")
                    {
                        string stringSql = strSqlToUpdateBStyleDB.ToString();
                        char[] charToTrim = new char[] { '|' };
                        string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                        return new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                    }
                    else
                    {
                        string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                        string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                        char[] charToTrim = new char[] { '|' };
                        string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                        string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                        LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                        return webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                    }



                }
                #endregion
                #region 不含担保交易
                else if (order.ORDER_SECDEAL == 0)
                {
                    StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                    StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                    Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                    if (userInfo == null)
                    {
                        throw new Exception("系统内无此会员信息！");
                    }
                    Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                    if (userAccount == null)
                    {
                        strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                        strSqlToUpdateBStyleDB.Append(userInfo.DM);
                        strSqlToUpdateBStyleDB.Append("',0)|");

                        strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                        strSqlToUpdateErpDB.Append(userInfo.DM);
                        strSqlToUpdateErpDB.Append("',0)|");
                    }

                    if (order.ORDER_CLEAR == 1)
                    {
                        if (IsUpdateDeliverCode)
                        {
                            strSqlToUpdateBStyleDB.Append("update ORDERDOC set ORDER_SEND=1,ORDER_SENDER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_SENDDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',ORDER_TRANBILLCODE='");
                            strSqlToUpdateBStyleDB.Append(deliverCode);
                            strSqlToUpdateBStyleDB.Append("',BYZD21='");
                            strSqlToUpdateBStyleDB.Append(pch);
                            strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(orderId);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }
                        else
                        {
                            strSqlToUpdateBStyleDB.Append("update ORDERDOC set ORDER_SEND=1,ORDER_SENDER='");
                            strSqlToUpdateBStyleDB.Append(operatorId);
                            strSqlToUpdateBStyleDB.Append("',ORDER_SENDDATE='");
                            strSqlToUpdateBStyleDB.Append(DateTime.Now);
                            strSqlToUpdateBStyleDB.Append("',BYZD21='");
                            strSqlToUpdateBStyleDB.Append(pch);
                            strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                            strSqlToUpdateBStyleDB.Append(orderId);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }
                        for (int i = 0; i < orderDetails.Count; i++)
                        {
                            strSqlToUpdateBStyleDB.Append("update SPKCB set SL=SL-");
                            strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_QTY);
                            strSqlToUpdateBStyleDB.Append(" where CKDM='");
                            strSqlToUpdateBStyleDB.Append(ConfigurationManager.AppSettings["ckdm"].ToString());
                            strSqlToUpdateBStyleDB.Append("' and KWDM='");
                            strSqlToUpdateBStyleDB.Append(ConfigurationManager.AppSettings["kwdm"].ToString());
                            strSqlToUpdateBStyleDB.Append("' and SPDM='");
                            strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_CMDCODE);
                            strSqlToUpdateBStyleDB.Append("' and GG1DM='");
                            strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_COLORCODE);
                            strSqlToUpdateBStyleDB.Append("' and GG2DM='");
                            strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_SIZECODE);
                            strSqlToUpdateBStyleDB.Append("'|");
                        }

                        decimal points = Convert.ToDecimal(0.00);
                        foreach (Model.ORDERDETAIL temp in orderDetails)
                        {
                            points += temp.OD_ADDITG;
                        }

                        string strUpdateVipSetSqlString = new BLL.V_VIPSET().BuildUpdateVipSetSqlString(0, 0, 0, order.ORDER_CUSTOMERCODE);
                        strSqlToUpdateBStyleDB.Append(strUpdateVipSetSqlString);
                        strSqlToUpdateErpDB.Append(strUpdateVipSetSqlString);

                        if (order.ORDER_PAYAMT - order.ORDER_AAMT > 0)
                        {
                            string strUpdateVipAccountSqlString = new BLL.V_VIP_ACCOUNT().BuildUpdateVipAccountSqlString(order.ORDER_PAYAMT - order.ORDER_AAMT, userInfo.DM);
                            strSqlToUpdateBStyleDB.Append(strUpdateVipAccountSqlString);
                            strSqlToUpdateErpDB.Append(strUpdateVipAccountSqlString);

                            string strInsertBalanceManagementSqlString = new BLL.BALANCEADJUST().BuildInsertMainSqlString("005", order.ORDER_ID, operatorId, operatorId, order.ORDER_CUSTOMERCODE, order.ORDER_PAYAMT - order.ORDER_AAMT);
                            strSqlToUpdateBStyleDB.Append(strInsertBalanceManagementSqlString);

                        }

                        string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                        string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                        char[] charToTrim = new char[] { '|' };
                        string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                        string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                        LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                        return webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);

                    }
                    else
                    {
                        throw new Exception("该订单未结算，因此不能发货！");
                    }
                }
                #endregion
            }
            #endregion
            #region 货到付款流程
            else if (order.ORDER_APAY == 1)
            {
                Model.V_VIPSET userInfo = new BLL.V_VIPSET().GetModel(order.ORDER_CUSTOMERCODE);
                if (userInfo == null)
                {
                    throw new Exception("系统内无此会员信息！");
                }
                Model.V_VIP_ACCOUNT userAccount = new BLL.V_VIP_ACCOUNT().GetModel(userInfo.DM);

                StringBuilder strSqlToUpdateBStyleDB = new StringBuilder();
                StringBuilder strSqlToUpdateErpDB = new StringBuilder();

                if (userAccount == null)
                {
                    strSqlToUpdateBStyleDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                    strSqlToUpdateBStyleDB.Append(userInfo.DM);
                    strSqlToUpdateBStyleDB.Append("',0)|");

                    strSqlToUpdateErpDB.Append("insert into v_vip_account(DM,DQJE_1) values('");
                    strSqlToUpdateErpDB.Append(userInfo.DM);
                    strSqlToUpdateErpDB.Append("',0)|");
                }

                if (IsUpdateDeliverCode)
                {
                    strSqlToUpdateBStyleDB.Append("update ORDERDOC set ORDER_SEND=1,ORDER_SENDER='");
                    strSqlToUpdateBStyleDB.Append(operatorId);
                    strSqlToUpdateBStyleDB.Append("',ORDER_SENDDATE='");
                    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                    strSqlToUpdateBStyleDB.Append("',ORDER_TRANBILLCODE='");
                    strSqlToUpdateBStyleDB.Append(deliverCode);
                    strSqlToUpdateBStyleDB.Append("',BYZD21='");
                    strSqlToUpdateBStyleDB.Append(pch);
                    strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                    strSqlToUpdateBStyleDB.Append(orderId);
                    strSqlToUpdateBStyleDB.Append("'|");
                }
                else
                {
                    strSqlToUpdateBStyleDB.Append("update ORDERDOC set ORDER_SEND=1,ORDER_SENDER='");
                    strSqlToUpdateBStyleDB.Append(operatorId);
                    strSqlToUpdateBStyleDB.Append("',ORDER_SENDDATE='");
                    strSqlToUpdateBStyleDB.Append(DateTime.Now);
                    strSqlToUpdateBStyleDB.Append("',BYZD21='");
                    strSqlToUpdateBStyleDB.Append(pch);
                    strSqlToUpdateBStyleDB.Append("' where ORDER_ID='");
                    strSqlToUpdateBStyleDB.Append(orderId);
                    strSqlToUpdateBStyleDB.Append("'|");
                }

                for (int i = 0; i < orderDetails.Count; i++)
                {
                    strSqlToUpdateBStyleDB.Append("update SPKCB set SL=SL-");
                    strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_QTY);
                    strSqlToUpdateBStyleDB.Append(" where CKDM='");
                    strSqlToUpdateBStyleDB.Append(ConfigurationManager.AppSettings["ckdm"].ToString());
                    strSqlToUpdateBStyleDB.Append("' and KWDM='");
                    strSqlToUpdateBStyleDB.Append(ConfigurationManager.AppSettings["kwdm"].ToString());
                    strSqlToUpdateBStyleDB.Append("' and SPDM='");
                    strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_CMDCODE);
                    strSqlToUpdateBStyleDB.Append("' and GG1DM='");
                    strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_COLORCODE);
                    strSqlToUpdateBStyleDB.Append("' and GG2DM='");
                    strSqlToUpdateBStyleDB.Append(orderDetails[i].OD_SIZECODE);
                    strSqlToUpdateBStyleDB.Append("'|");
                }

                if (strSqlToUpdateErpDB.ToString() == "")
                {
                    string stringSql = strSqlToUpdateBStyleDB.ToString();
                    char[] charToTrim = new char[] { '|' };
                    string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                    return new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray);
                }
                else
                {
                    string stringSqlToUpdateBStyleDB = strSqlToUpdateBStyleDB.ToString();
                    string stringSqlToUpdateErpDB = strSqlToUpdateErpDB.ToString();

                    char[] charToTrim = new char[] { '|' };
                    string[] strArray1 = stringSqlToUpdateBStyleDB.TrimEnd(charToTrim).Split(charToTrim);
                    string[] strArray2 = stringSqlToUpdateErpDB.TrimEnd(charToTrim).Split(charToTrim);

                    LX_Manage.ERP.Service webService = new LX_Manage.ERP.Service();
                    return webService.UpdateBalanceAndUsableDeliverAmountOfOneRecord(ConfigurationManager.AppSettings["WebServiceKey"].ToString(), strArray1, strArray2);
                }
            }
            #endregion

            else
            {
                return false;
            }
        }
        else
        {
            throw new Exception("查询数据时出现错误，请重新执行发货操作！");
        }
        return false;

    }

    #endregion

    //#region 回调方法
    //public void RaiseCallbackEvent(string eventArgument)
    //{
    //    try
    //    {
    //        this.programmaticModalPopup.Show();
    //        if (!this.IsSend)
    //        {
    //            if (!Check.CheckPermission("500100", "00014"))
    //            {
    //                Share.Alert(this.Page, "无权操作"); return;
    //            }

    //            bool result = Deliver(this.Code, Share.UserValue(0), true, eventArgument);
    //            if (result)
    //            {
    //                strResult = "1";
    //            }
    //            else
    //            {
    //                strResult = "0";
    //            }
    //        }
    //        else
    //        {
    //            if (!Check.CheckPermission("500100", "00017"))
    //            {
    //                Share.Alert(this.Page, "无权操作"); return;
    //            }
    //            bool result = new BLL.ORDERDOC().UpdateDeliverCode(this.Code, eventArgument);
    //            if (result)
    //            {
    //                strResult = "2";
    //            }
    //            else
    //            {
    //                strResult = "3";
    //            }
    //        }
    //        this.programmaticModalPopup.Hide();
    //    }
    //    catch
    //    {
    //        strResult = "0";
    //    }
    //}

    //public string GetCallbackResult()
    //{
    //    return strResult;
    //}
    //#endregion

    protected void btnHiddenShip_Click(object sender, EventArgs e)
    {
        try
        {
            this.programmaticModalPopup.Show();
            HtmlInputText txtDeliverCode = (HtmlInputText)dlistMainInvoice.Items[0].FindControl("txtDeliverCode");
            if (txtDeliverCode == null)
            {
                this.programmaticModalPopup.Hide();
                Share.Alert(this.Page, "发货失败，请重新操作！"); return;
            }
            Model.PICI pc = new BLL.PICI().GetModel(Share.UserValue(0), "PCH_ID");
            if (pc == null)
            {
                Share.Alert(this.Page, "请先开始一个批次"); return;
            }

            Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(this.Code);
            if (order != null)
            {
                if (order.ORDER_SEND == 0)
                {
                    if (!Check.CheckPermission("500100", "00014"))
                    {
                        this.programmaticModalPopup.Hide();
                        Share.Alert(this.Page, "无权操作"); return;
                    }

                    bool result = Deliver(this.Code, Share.UserValue(0), true, txtDeliverCode.Value, pc.PCH_ID);
                    if (result)
                    {
                        Response.Write("<script>alert('发货成功！');window.location.href='invoices.aspx'</script>");
                    }
                    else
                    {
                        this.programmaticModalPopup.Hide();
                        Share.Alert(this.Page, "发货失败");
                    }
                }
                else
                {
                    if (!Check.CheckPermission("500100", "00017"))
                    {
                        this.programmaticModalPopup.Hide();
                        Share.Alert(this.Page, "无权操作"); return;
                    }
                    bool result = new BLL.ORDERDOC().UpdateDeliverCode(this.Code, txtDeliverCode.Value);
                    if (result)
                    {
                        this.programmaticModalPopup.Hide();
                        Share.InsertLog("500100", "00017");
                        Share.Alert(this.Page, "物流单号修改成功！");
                    }
                    else
                    {
                        this.programmaticModalPopup.Hide();
                        Share.Alert(this.Page, "物流单号修改失败！");
                    }
                }
                this.programmaticModalPopup.Hide();
            }
        }
        catch (Exception ex)
        {
            this.programmaticModalPopup.Hide();
            Share.Alert(this.Page, ex.Message);
        }

    }
    protected void btnUpdateDeliverInfo_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("500100", "00017"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        HtmlInputText txtDeliverCode = (HtmlInputText)dlistMainInvoice.Items[0].FindControl("txtDeliverCode");
        DropDownList dropTraner = (DropDownList)dlistMainInvoice.Items[0].FindControl("dropTraner");
        if (txtDeliverCode.Value.Length <=4)
        {
            Share.Alert(this.Page, "物流单号不允许少于4个字符长度！"); return;
        }
        DataSet ds=null;
        string ret = new BLL.ORDERDOC().GetOrderByWhere(string.Format(" where ORDER_TRANBILLCODE ='{0}' and ORDER_ID not in('{1}') ",txtDeliverCode.Value,this.Code), out ds);
        if (ds.Tables[0].Rows.Count>0)
        {
            Share.Alert(this.Page, "物流单号不允许重复！"); return;
        }
        bool result = new BLL.ORDERDOC().UpdateDeliverCode(this.Code, txtDeliverCode.Value, dropTraner.SelectedValue);
        if (result)
        {
            Share.InsertLog("500100", "00017");
            Share.Alert(this.Page, "物流单号修改成功！");
        }
        else
        {
            Share.Alert(this.Page, "物流单号修改失败！");
        }
    }
    protected void btnLock_Click(object sender, EventArgs e)
    {
        string sql = "UPDATE [ORDERDOC] SET byzd13=1,BYZD20='" + Share.UserValue(0) + "', BYZD10='" + DateTime.Now.ToString() + "' WHERE [ORDER_ID]='" + this.Code + "'";
        int ret = new BLL.Jet().CountRunSql(sql);
        if (ret > 0)
        {
            ButtonStatus();
        }
        else
        {
            Share.Alert(this, "锁定失败!");
        }
    }
    protected void btnUnlock_Click(object sender, EventArgs e)
    {
        string sql = "UPDATE [ORDERDOC] SET byzd13=0,BYZD20='', BYZD10='" + DateTime.MinValue.ToString() + "' WHERE [ORDER_ID]='" + this.Code + "'";
        int ret = new BLL.Jet().CountRunSql(sql);
        if (ret > 0)
        {
            ButtonStatus();
        }
        else
        {
            Share.Alert(this, "解锁失败!");
        }
    }
    private void ButtonStatus()
    {
        Model.SYSPARAM sys = new BLL.SYSPARAM().GetModel("010");
        if (sys == null)
        {
            btnLock.Visible = false;
            btnUnlock.Visible = false;
            btnDeliverPrint.Enabled = true;
            btnExpressPrint.Enabled = true;
        }
        else
        {
            if (sys.SP_PARAM1 != 1)
            {
                btnLock.Visible = false;
                btnUnlock.Visible = false;
                btnDeliverPrint.Enabled = true;
                btnExpressPrint.Enabled = true;
            }
            else
            {
                DataSet dst = new BLL.ORDERDOC().GetOrder(this.Code);
                if (dst != null && dst.Tables[0].Rows.Count > 0)
                {
                    string _lock = dst.Tables[0].Rows[0]["BYZD13"].ToString();
                    string _locker = dst.Tables[0].Rows[0]["BYZD20"].ToString();
                    if (_lock == "1")
                    {
                        if (_locker == Share.UserValue(0))
                        {
                            btnLock.Visible = true;
                            btnLock.Enabled = false;
                            btnUnlock.Visible = true;
                            btnUnlock.Enabled = true;
                            btnDeliverPrint.Enabled = true;
                            btnExpressPrint.Enabled = true;
                        }
                        else
                        {
                            btnLock.Visible = true;
                            btnLock.Enabled = false;
                            btnUnlock.Visible = true;
                            btnUnlock.Enabled = false;
                            btnDeliverPrint.Enabled = false;
                            btnExpressPrint.Enabled = false;
                        }
                    }
                    else
                    {
                        btnLock.Visible = true;
                        btnUnlock.Visible = true;
                        btnUnlock.Enabled = false;
                        btnDeliverPrint.Enabled = false;
                        btnExpressPrint.Enabled = false;
                    }
                }
            }
        }
    }
    
}
